package cn.boyu.service.impl;

import cn.boyu.entity.Customer;
import cn.boyu.entity.SysUser;
import cn.boyu.exception.LogicException;
import cn.boyu.mapper.SysUserMapper;
import cn.boyu.query.SysUserQuery;
import cn.boyu.result.AjaxResult;
import cn.boyu.result.AssertUtil;
import cn.boyu.result.IDUtils;
import cn.boyu.service.ISysUserService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.netty.handler.timeout.IdleState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yn
 * @since 2022-11-22
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser login(String username, String password) {
        QueryWrapper<SysUser> qw = new QueryWrapper<>();
        qw.eq("user_name", username);
        qw.eq("password", password);
        SysUser user = getOne(qw);
        if (user == null) {
            throw new LogicException("用户名或密码错误");
        }
        return user;
    }

    @Override
    public String setToken(SysUser userinfo) {
        String token = UUID.randomUUID().toString().replace("-", "");
        String key = "token:" + token;
        redisTemplate.opsForValue().set(key, userinfo.getUserId().toString(), 30, TimeUnit.MINUTES);
        System.err.println("设置成功"+token);
        return token;
    }

    @Override
    public AjaxResult editPassword(Long id, String password, String newPass, String rePass) {
        SysUser user = sysUserMapper.selectById(id);

        if (user.getPassword().equals(password)) {
            //原密码正确
            if (newPass.equals(rePass)) {
                //改库
                UpdateWrapper<SysUser> wrapper = new UpdateWrapper<>();
                wrapper.eq("user_id", id).set("password", newPass);
                sysUserMapper.update(null, wrapper);
                return AjaxResult.success("修改成功");
            } else {
                return AjaxResult.error("两次密码不一致");
            }
        } else {
            return AjaxResult.error("原密码错误");
        }
    }

    @Override
    public SysUser getUserByToken(String token) {
        System.out.println("token传参:" + token);
        if (!StringUtils.hasLength(token)) {
//            throw new LogicException("未登录");
            return null;
        }
        String key = "token:" + token;
        if (redisTemplate.hasKey(key)) {
            String value = redisTemplate.opsForValue().get(key);
            SysUser user = sysUserMapper.selectById(value);
            return user;
        } else {
//            throw new LogicException("redis服务器故障");
            return null;
        }

    }

    @Override
    public void register(String name, String nick, String phone, String password, String rePass) {
        AssertUtil.hasLength(name, "账号不能为空！");
        AssertUtil.hasLength(nick, "昵称不能为空！");
        AssertUtil.hasLength(phone, "手机号码不能为空！");
        AssertUtil.hasLength(password, "密码不能为空！");
        AssertUtil.hasLength(rePass, "确认密码不能为空！");
        AssertUtil.isEquals(password, rePass, "两次密码不一致");

        if (checkName(name)) {
            throw new LogicException("改账号已被注册！");
        }

        SysUser user = new SysUser();
        user.setUserName(name);
        user.setNickName(nick);
        user.setPhonenubmber(phone);
        user.setPassword(password);
        user.setSex("0");
        user.setUserType("00");
        user.setAvatar("http://");
        user.setEmail("填写邮箱");
        save(user);
    }


    private boolean checkName(String name) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", name);
        SysUser user = this.getOne(wrapper);
        return user != null;
    }

    @Override
    public IPage<SysUser> queryPage(SysUserQuery qo) {
        IPage<SysUser> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        QueryWrapper<SysUser> qw = new QueryWrapper<>();
        qw.like(qo.getUserName() != null && qo.getUserName() != "", "user_name", qo.getUserName());
        qw.eq("del_flg", 0);
        return this.page(page, qw);
    }

    @Override
    public void update(SysUser sysUser) {
        sysUserMapper.updateById(sysUser);
    }

    @Override
    public void batchDelete(Long[] ids) {
        sysUserMapper.batchDelete(ids);
    }

    @Override
    public void savesys(SysUser sysUser) {
        sysUserMapper.insert(sysUser);
    }

}
